<template>
    <div class="teamWrapp">
        <div class="title">测试执行</div>
        <div class="itemLine"><el-input placeholder="请输入内容">
    <template slot="prepend">品牌ID</template>
  </el-input><el-button icon="el-icon-search">搜索</el-button><el-button @click="addCase">+添加</el-button></div>
      <div id="time" style="display:none">
           <el-date-picker
      v-model="time"
      type="daterange"
      range-separator="至"
      start-placeholder="开始日期"
      format="yyyy 年 MM 月 dd 日"
      value-format="yyyy-MM-dd"
      end-placeholder="结束日期">
    </el-date-picker>
    </div>
      <div id="paramssdfsdf">
              <table class="hovertable">
                <tr>
                  <th>测试用例名称</th><th>产品名称</th><th>产品类型</th><th>设备唯一标识</th><th>设备唯一标识类型</th><th>开始时间</th><th>结束时间</th><th>创建时间</th><th>操作</th>
                </tr>
                <tr onmouseover="this.style.backgroundColor='rgb(236,236,236)';" onmouseout="this.style.backgroundColor='#fff';" v-for="(item,index) in caseList">
                  <td>{{item.test_name}}</td><td>{{item.product_name.name}}</td><td>{{item.product_type}}</td><td>{{item.unique}}</td><td>{{item.unique_type}}</td><td>{{item.start_time}}</td>
                  <td>{{item.end_time}}</td><td>{{item.create_time}}</td>
                  <td>
                      <el-button size="mini" @click="implement(index)" icon="el-icon-sort">执行</el-button>
                      <el-button size="mini" @click="delCase(index)" icon="el-icon-delete">删除</el-button>
                      <el-button size="mini" @click="sendM(index)" icon="el-icon-sort">样机寄送</el-button>
                  </td>                
                </tr>
              </table>
          </div>
    </div>
</template>

<script>
  import $ from 'jquery'
  import _ from 'underscore'
    export default {
        activated(){
          $('.el-input__inner')[0].setAttribute("style","border: 1px solid #dadce2 !important")
          localStorage.setItem('switch',0)
          this.get_add_test_info()
          this.getCaseList()
        },
        data() {
          return {
            caseList:[],
            //
            company:[],
            brand:[],
            product:[],
            time:'',
            choosePdMac:'',
            uuidCode:'1e3fd0aef00c3c1cf4ae3d423737954c',
            timeDom:{},
            checkedOff:false
          }
         },
    methods: {
      delCase(index) {
        setTimeout(()=>{
        $('.el-button--primary')[0].setAttribute("style","background-color: rgb(58, 19, 90) !important;border-color: rgb(58, 19, 90) !important")
          
        },10)
        this.$confirm('是否删除该用例?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
              var pid=this.caseList[index].id
              var data={token:localStorage.getItem('token'),id:pid}
              this.$http.post(this.$store.getters.serverIp+'delete_test_case',data).then((response)=>{
                if(response.data.success){
                  this.caseList.splice(index,1)
                    this.$message.success({
                      type: 'success',
                      message: '删除成功!',
                      duration:1000
                    });
                  }
                }).catch(()=>{
              })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
          });          
        });
      },
      sendM(index){
        var data={id:this.caseList[index].id,token:localStorage.getItem('token')}
         this.$http.post(this.$store.getters.serverIp+'get_one_test_info',data).then((response)=>{
           var str=`
              <div id="infosdfsdfdsf">
                <span>产品名称：</span><div><input class="mybutton" id="product_name_y" disabled value=${response.data.name} /></div>
                <span>产品类型：</span><div><input class="mybutton" id="product_type_y" disabled value=${response.data.product_type} /></div>
                <div><span>样机寄送类型：</span><div><select class="mybutton" id="send_type"/>
                    <option value="普通产品">快递</option>
                    <option value="路由器">亲自上门</option>
                </select></div>
                <span>快递单号：</span><div><input class="mybutton" id="send_number"  /></div>
                <span>软件版本号：</span><div><input class="mybutton" id="version"  /></div>
                <div><span>唯一标识类型：</span><div><select class="mybutton" id="unique_type_y"/>
                    <option value="普通产品">快递</option>
                    <option value="路由器">亲自上门</option>
                </select></div>
                <span>设备mac1：</span><div><input class="mybutton" id="mac1"  /></div>
                <span>设备mac2：</span><div><input class="mybutton" id="mac2"  /></div>
                <span>设备mac3：</span><div><input class="mybutton" id="mac3"  /></div>
                <span>发件人名称：</span><div><input class="mybutton" id="send_name"  /></div>
                <span>联系电话：</span><div><input class="mybutton" id="send_phone"  /></div>
                <span>邮箱：</span><div><input class="mybutton" id="send_email"  /></div>
                <span>发件地址：</span><div><input class="mybutton" id="send_addr"  /><input class="mybutton" id="test_case_id"  value=${this.caseList[index].id} type="hidden"/></div>
              </div>
           `
           this.$alert(str, {
                        dangerouslyUseHTMLString: true,
                        callback:this.addSendM,
                        title:'样机寄送'
           
         })
           setTimeout(()=>{
            $('.el-message-box')[0].setAttribute("style","width: 398px !important;")
            $('.el-button--primary')[0].setAttribute("style","background-color: rgb(58, 19, 90) !important;border-color: rgb(58, 19, 90) !important")
          },10)
        });
      },
      get_add_test_info(){
        this.$http.post(this.$store.getters.serverIp+'get_add_test_info',{token:localStorage.getItem('token')}).then((response)=>{
            if(response.data.success){
                this.company=response.data.company
                this.brand=response.data.brand
                this.product=response.data.product
            }
        })
      },
      implement(index){
        if(this.$store.getters.isConnectMqtt==false){
          this.$message.error({message:'mqtt服务器连接失败',duration:1000});
          return
        }
        this.choosePdMac=this.caseList[index].unique
        console.log(this.choosePdMac,index)
        var str=`
          <div class="implementWrap">
            <div class="pStatus">
              <div class="titlesd">设备状态</div>
              <div class="showMessage"></div>
            </div>
            <div class="pStatuss">
              <div class="titlesd">接收信息</div>
              <div class="showMessage"></div>
            </div>
            <div class="pStatus">
              <div class="titlesd">功能列表</div>
              <div class="implement showMessage">
                <span>开关：</span>
                <div class="choseWrap" id="switch">
                  <div>开</div>
                  <div class="active">关</div>
                </div>
              </div>
            </div>
          </div>`
        this.$alert(str, {
                      dangerouslyUseHTMLString: true,
                      callback:this.implementServer,
                      title:'执行',
                      confirmButtonText:'确定执行',
                      showCancelButton:true
        });
        setTimeout(function(){
          $('#switch>div').click(function(event) {
              var index=$(this).index()
              $(this).siblings().removeClass('active')
              $(this).addClass('active')
              if(index===1){
                localStorage.setItem('switch',0)
              }else{
                localStorage.setItem('switch',1)
              }
          });
          $('.el-button--primary')[0].setAttribute("style","background-color: rgb(58, 19, 90) !important;border-color: rgb(58, 19, 90) !important")
          $('.el-message-box')[0].setAttribute("style","width: 798px !important;")
        },10)
      },
      implementServer(action){
        if(action=="confirm"){
          this.getDeviceUuid(1)
        } 
      },
      addCase(){
        if(this.$store.getters.isConnectMqtt==false){
          this.$message.error({message:'mqtt服务器连接失败',duration:1000});
          return
        }
        var str=`
          <div id="infosdfsdf" class="myAlert"><span>厂商名称：</span><div><select class="mybutton" id="company"/>
          <option value=${this.company.id}>${this.company.full_name}</option>
                                              </select></div>
                                              <div><span>品牌名称：</span><div><select class="mybutton" id="brand"/>`
          for(var i=0;i<this.brand.length;i++){
            str+=`<option value=${this.brand[i].id}>${this.brand[i].name}</option>`
          }
          str+=`</select></div><div><span>产品名称：</span><div><select class="mybutton" id="product"/>` 
          for(var i=0;i<this.product.length;i++){
            str+=`<option value=${this.product[i].id}>${this.product[i].name}</option>`
          }
          str+=`</select></div>`
          str+=`<div><span>产品类型：</span><div><select class="mybutton" id="productType"/>
                    <option value="普通产品">普通产品</option>
                    <option value="路由器">路由器</option>
                    <option value="天翼网关">天翼网关</option>
                    <option value="应用网关">应用网关</option>
                </select></div>`
         str+=`<div><span>标识类型：</span><div><select class="mybutton" id="unique_type"/>
                    <option value="MAC">MAC</option>
                </select></div>`
          str+=`<div><span>测试名称：</span><div><input type="text" class="mybutton" id="testN"><div><span>设备终端唯一编码：</span><div><input type="text" class="mybutton" id="unique"></div><span>起始时间：</span></div>`
        this.$alert(str, {
                      dangerouslyUseHTMLString: true,
                      callback:this.addCaseSever,
                      title:'添加测试执行'
        });
        window.setTimeout(()=>{
          if(!$('#infosdfsdf').find('.el-date-editor').length){
            if($('.el-date-editor').length){
              this.timeDom=$('.el-date-editor')
            }
            $('#infosdfsdf').append(this.timeDom)
          }
          $('.el-button--primary')[0].setAttribute("style","background-color: rgb(58, 19, 90) !important;border-color: rgb(58, 19, 90) !important")
          $('.el-message-box')[0].setAttribute("style","width: 398px !important;")
        },10)
      },
      addCaseSever(action){
        if(action=="confirm"){
        var data={token:localStorage.getItem('token'),brand_id:$('#brand').val(),product_id:$('#product').val(),test_name:$('#testN').val(),product_type:$(productType).val(),
          start_time:this.time[0],end_time:this.time[1],unique_type:$('#unique_type').val(),unique:$('#unique').val()
        } 
        var hasEmpty=false
         _.each(data,(value)=>{
              if($.trim(value)==''){
                  hasEmpty=true
              }
          })
          if(hasEmpty){
              this.$message.error({message:'信息不能为空',duration:1000});
              return
          }
          this.$http.post(this.$store.getters.serverIp+'add_test_case',data).then((response)=>{
              if(response.data.success){
                this.$message.success({message:response.data.info,duration:1000});
                this.getCaseList()
                this.getDeviceUuid()
              }
          })
        }
      },
      getDeviceUuid(flag){
          if(!flag){
            var data={mac:$('#unique').val(),code:this.uuidCode,version:2}
          }else{
            var data={mac:this.choosePdMac,code:this.uuidCode,version:2}
          }  
          this.$http.get(this.$store.getters.serverIpA+`/home/uuid/create_uuid?mac=${data.mac}&code=${data.code}&version=${data.version}`,data).then((response)=>{
               var uuid=response.data
               //订阅
               var topic=`2018/${uuid}/toapp`
               this.$mqtt.subscribe(topic)
               if(!flag){
                 this.sendMqttServer(uuid)
               }else{
                 this.sendMqttServer(uuid,1)
               }
          })
      },
      sendMqttServer(uuid,flag){
        if(!flag){//添加测试用例 后自动发送一条mqtt
          var sendData={cmd:2001,uuid:uuid,mac:$('#unique').val(),type:'none',status:1}
        }else{//手动执行发送一条mqtt
          var sendData={cmd:2001,uuid:uuid,mac:this.choosePdMac,type:'none',status:Number(localStorage.getItem('switch'))}
        }
        console.log(sendData)
        //发送
        this.$mqtt.publish(`2018/${uuid}/todev`,JSON.stringify(sendData))
      },
      addSendM(action){
        if(action=="confirm"){
          var data={
            test_case_id:Number($('#test_case_id').val()),send_type:$('#send_type').val(),send_number:$('#send_number').val,version:$('#version'),
            unique_type:$('#unique_type_y').val(),mac1:$('#mac1').val(),mac2:$('#mac2').val(),mac3:$('#mac3').val(),send_name:$('#send_name').val(),send_phone:$('#send_phone').val(),send_email:$('#send_email').val(),send_addr:$('#send_addr').val(),token:localStorage.getItem('token')
          }
          var hasEmpty=false
           _.each(data,(value)=>{
              if($.trim(value)==''){
                  hasEmpty=true
              }
          })
          if(hasEmpty){
              this.$message.error({message:'信息不能为空',duration:1000});
              return
          }
          data.unique=data.mac1+','+data.mac2+','+data.mac3
          this.$http.post(this.$store.getters.serverIp+'add_sample',data).then((response)=>{
              if(response.data.success){
                this.$message.success({message:response.data.info,duration:1000});
              }else{
                this.$message.error({message:response.data.info,duration:1000});
              }
          })
        }
      },
      getCaseList(){
          this.$http.post(this.$store.getters.serverIp+'get_test_case_list',{token:localStorage.getItem('token')}).then((response)=>{
                var caseList=response.data.data
                caseList=_.map(caseList,(value)=>{
                    var date = new Date(value.create_time * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
                    var Y = date.getFullYear() + '-';
                    var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
                    var D = date.getDate() + ' ';
                    var create_time=Y+M+D;
                    value.create_time=create_time
                    return value
                })
                this.caseList=caseList
          })
      }
    },
     mqtt: {
    '#' (data, topic) {
      console.log(topic + ': ' + String.fromCharCode.apply(null, data))
    }
  }
    }
</script>
<style lang="less" >
    .teamWrapp{
      #paramssdfsdf{
        box-sizing: border-box;
        padding: 1% 2%;
      }
        .el-input__inner{
          border: 1px solid #d2d8e8;
        }
        .el-table{
            margin: 0 auto !important;
            .is-leaf {
                border-bottom: 1px solid #c2cbe2 !important;
                text-align: center;
            }
            .cell{
                text-align: center !important;
            }
        }
        .itemLine{
            margin: 6px;
            .el-input-group{
              width: 10%;
              margin-right: 9px;
            }
        }
        .el-table__header-wrapper{
        font-size: 22px !important;
        }
        tr.el-table__row {
            font-size: 18px;
        }
       
    }
      .el-message-box {
           width: 398px !important;
      }
      .el-date-editor{
          width: 101% !important;
      }
      .implementWrap{
        >div{
          float: left;
          height: 250px;
            text-align: center;
            margin-right: 20px;
        }
        .pStatus{
            width: 159px;
        }
        .pStatuss{
            width: 359px;
        }
        .showMessage{
            height: 80%;
            box-shadow: 0 2px 10px 4px rgba(0, 0, 0, 0.2);
            overflow: auto;
                padding: 3%;
                box-sizing:border-box;
        }
        .implement{
          >span{
            display: block;
            float: left;
            font-size: 15px;
          }
          .choseWrap{
            height: 30px;
            display: inline-block;
            width: 103px;
            >div{
              text-align: center;
              float: left;
              font-size: 13px;
              width: 30px;
              margin-left: 14%;
              box-shadow: 0 1px 10px 3px rgba(0, 0, 0, 0.2);
              &:hover{
                cursor:pointer;
              }
            }
            .active{
              background: blanchedalmond;
            }
          }
        }
      }
</style>>